<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Selibra\WebSocket\Interceptor;


use Selibra\Tools\Console;
use Selibra\Di\Annotations\Autowired;

class ActionSpaceInterceptorCollector
{

    /**
     * @var ActionSpaceTree
     */
    protected static ActionSpaceTree $actionSpaceTree;


    /**
     * @param string $name
     * @param $class
     * @param $method
     */
    public static function register(string $name, $class, $method)
    {
        $actionSpaceArray = array_filter(explode('/', $name));
        // 添加节点
        $actionSpaceNode = new ActionSpaceNode($actionSpaceArray[count($actionSpaceArray) - 1]);
        $actionSpaceNode->setNamespace($class);
        $actionSpaceNode->setMethod($method);
        self::getActionSpaceTree()->addNode($actionSpaceArray, $actionSpaceNode);
    }


    /**
     * @return ActionSpaceTree
     */
    public static function getActionSpaceTree()
    {
        if (empty(self::$actionSpaceTree)) {
            self::$actionSpaceTree = new ActionSpaceTree();
        }
        return self::$actionSpaceTree;
    }


    /**
     * @param string $action
     * @return array
     */
    public static function getInterceptors(string $action)
    {
        $actionSpaceArray = array_filter(explode('/', $action));
        // 查找
        $i = 0;
        $interceptors = [];
        $parentActionSpace = $actionSpaceArray;
        array_pop($parentActionSpace);
        foreach ($parentActionSpace as $item) {
            $actionSpace = array_slice($parentActionSpace, 0, $i + 1);
            $actionSpace[] = '*';
            $nodes = self::getActionSpaceTree()->getNodes($actionSpace);
            if (!empty($nodes)) {
                $interceptors = array_merge($interceptors, $nodes);
            }
            $i++;
        }
        $actionSpaceArray[] = '/';
        $rootNodes = self::getActionSpaceTree()->getNodes($actionSpaceArray);
        $interceptors = array_merge($interceptors, $rootNodes);
        return $interceptors;
    }

}